"use client";

import React, { useState } from "react";
import { useRouter } from 'next/navigation';
import { try_login, try_register } from "./services/api";

export default function Home() {
  const [userId, setUserId] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [isRegistering, setIsRegistering] = useState(false); // 用于切换登录和注册的状态
  const router = useRouter();

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    try {
      const response = await try_login(userId, password);
      if (response.success && response.userId) {
        // 存储 userId 用于后续请求
        localStorage.setItem('userId', response.userId);
        router.push(`/choose?userId=${encodeURIComponent(response.userId)}`);
      } else {
        setError(response.message || "登录失败。请检查您的凭据。");
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "登录失败");
    }
  };

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(""); // 清除之前的错误
    if (!userId || !password) {
        setError("用户ID和密码不能为空。");
        return;
    }
    let json_val = await try_register(userId, password);
    let isSuccess= json_val["success"];
    let message = json_val["message"];
    if (isSuccess) {
      // 可选：显示成功消息并切换到登录
      setError("注册成功！请登录。");

      setIsRegistering(false); // 切换回登录视图
    } else {
      setError(message || "注册失败。请稍后再试。");
    }
  };

  const changeMode = () => {
    setIsRegistering(!isRegistering);
    setError(""); // 切换模式时清除错误
    setUserId(""); // 切换模式时清除字段
    setPassword("");
  };

  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900">
      <form
        onSubmit={isRegistering ? handleRegister : handleLogin}
        className="w-full max-w-sm bg-white dark:bg-gray-800 p-8 rounded-lg shadow-lg" // 为典型的认证表单调整了最大宽度
      >
        <h1 className="text-xl font-bold text-center mb-6 dark:text-white">
          {isRegistering ? '注册' : '登录'}
        </h1>

        {error && (
          <div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded text-sm">
            {error}
          </div>
        )}

        <div className="mb-4">
          <label htmlFor="userId" className="block text-sm font-medium text-gray-700 dark:text-gray-300">用户ID</label>
          <input
            id="userId"
            type="text"
            value={userId}
            onChange={(e) => setUserId(e.target.value)}
            required
            className="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:bg-gray-700 dark:text-gray-300"
          />
        </div>

        <div className="mb-6">
          <label htmlFor="password"className="block text-sm font-medium text-gray-700 dark:text-gray-300">密码</label>
          <input
            id="password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            className="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:bg-gray-700 dark:text-gray-300"
          />
        </div>

        <button
          type="submit"
          className="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
        >
          {isRegistering ? '注册' : '登录'}
        </button>

        <p className="mt-4 text-center text-sm text-gray-600 dark:text-gray-400">
          {isRegistering ? '已有账户？ ' : "没有账户？ "}
          <button
            type="button"
            onClick={changeMode}
            className="font-medium text-indigo-600 hover:text-indigo-500 focus:outline-none"
          >
            {isRegistering ? '在此登录' : '在此注册'}
          </button>
        </p>
      </form>
    </div>
  );
}
